/**
 * 公司管理
 */
import { Op } from 'sequelize'
import BaseBusinessController from './../base/BaseBusinessController'

class AdminCompanyController extends BaseBusinessController {

    /**
     * 公司列表
     * @return {[type]} [description]
     */
    async actionColumn() {
        let { search, region_id, building_id } = $_POST;
        let where = {};

        let buildingIds = await super.buildingIds(this.state.user.id);
        if (buildingIds) {
            where['building_id'] = {
                [Op.in]:buildingIds
            }
        }

        if (search) {
            where['name'] = {
                [Op.like]: '%' + search + '%'
            }
        }
        if (region_id) {
            where['region_id'] = region_id;
        }
        if (building_id) {
            where['building_id'] = building_id;
        }

        return await this.modules('Company').where(where).fields(['id', 'name', 'building_id', 'region_id']).order([
            ['id', 'DESC']
        ]).select();
    }

    /**
     * 公司列表
     * @return {[type]} [description]
     */
    async actionIndex() {
        let { page, search, region_id, building_id } = $_POST;
        let number = page && page.number !== undefined ? page.number : 1;
        let size = page && page.size !== undefined ? page.size : 20;
        let where = {};

        let buildingIds = await super.buildingIds(this.state.user.id);
        if (buildingIds) {
            where['building_id'] = {
                [Op.in]:buildingIds
            }
        }
        
        if (search) {
            where['name'] = {
                [Op.like]: '%' + search + '%'
            }
        }
        if (region_id) {
            where['region_id'] = region_id;
        }
        if (building_id) {
            where['building_id'] = building_id;
        }

        return await this.modules('Company').where(where).joinWith(['region', 'building', 'room']).page(number, size).order([
            ['id', 'DESC']
        ]).select();
    }

    /**
     * 公司详情
     * @return {[type]} [description]
     */
    async actionView() {
        let id = $_POST['id'];
        let data = await this.modules('Company').where({ id }).joinWith(['region', 'building', 'room']).first();
        if (data) {
            return data;
        } else {
            throw new Error('数据不存在');
        }
    }

    /**
     * 新增公司
     * @return {[type]} [description]
     */
    async actionCreate() {
        let { building_id, name, room_ids, uid } = $_POST;
        let check = await this.modules('Company').where({ building_id, name }).first();
        if (check) {
            throw new Error('公司已存在');
        }
        let userInfo = null;
        let accountInfo = null;
        if (uid) {
            userInfo = await this.modules('User').where({id:uid}).first();
            if (!userInfo) {
                throw new Error('用户不存在');
            }
            if (!userInfo.mobile || !userInfo.id_card) {
                throw new Error('请先绑定手机和身份证');
            }
            accountInfo = await this.modules('Account').where({mobile:userInfo.mobile,id_card:userInfo.id_card}).first();
            if (accountInfo && accountInfo.company_id) {
                throw new Error('请勿重复创建公司');
            }
            delete $_POST['uid'];
        }
        let t = await db.transaction();
        try {
            let roomWhere = null;
            if (room_ids && room_ids.length) {
                roomWhere = { building_id, company_id: 0 };
                roomWhere['id'] = {
                    [Op.in]: room_ids
                }
            }
            delete $_POST['room_ids'];
            let data = await this.modules('Company').insert($_POST, { transaction: t });
            if (data) {
                if (roomWhere) {
                    let res = await this.modules('Building.Room').where(roomWhere).update({ company_id: data.id }, { transaction: t });
                    if (!res) {
                        throw new Error('保存失败');
                    }
                }
                if (userInfo) {
                    if (accountInfo) {
                        let accountRes = await this.modules('Account').where({id:accountInfo.id}).update({ company_id: data.id }, { transaction: t });
                        if (!accountRes) {
                            throw new Error('保存失败');
                        }
                    } else {
                        let accountData = {
                            company_id:data.id,
                            user_name:userInfo.mobile,
                            mobile:userInfo.mobile,
                            real_name:userInfo.real_name,
                            id_card:userInfo.id_card,
                            app_id:3,
                            is_disable:0,
                            is_admin:0
                        }
                        let accountRes = await this.modules("Account").insert(accountData, { transaction: t });
                        if (!accountRes) {
                            throw new Error('保存失败');
                        }
                    }
                }
                await t.commit();
                return data;
            } else {
                throw new Error('保存失败');
            }
        } catch (error) {
            await t.rollback();
            throw error;
        }
    }
    /**
     * 新增公司(批量)
     * @return {[type]} [description]
     */
    async actionBulkCreate() {
        let { upData } = $_POST;
        let nams=upData.map(p=>p.name);
        let building_id=upData[0].building_id
        let check = await this.modules('Company').where({ building_id, name:nams }).first();
        if (check) {
            throw new Error('公司已存在');
        }
     
        let t = await db.transaction();
        try {
           
            let data = await this.modules('Company').bulkCreate($_POST.upData, { transaction: t });
            if (data) {
                await t.commit();
                return data;
            } else {
                throw new Error('保存失败');
            }
        } catch (error) {
            await t.rollback();
            throw error;
        }
    }
    /**
     * 编辑公司
     * @return {[type]} [description]
     */
    async actionUpdate() {
        let { id, building_id, name, room_ids } = $_POST;
        let check = await this.modules('Company').where({ building_id, name }).first();
        if (check && check.id != id) {
            throw new Error('公司不能重复');
        }
        let t = await db.transaction();
        try {
            let roomWhere = null;
            if (room_ids && room_ids.length) {
                roomWhere = { building_id, company_id: 0 };
                roomWhere['id'] = {
                    [Op.in]: room_ids
                }
            }
            delete $_POST['room_ids'];
            let data = await this.modules('Company').where({ id }).update($_POST, { transaction: t });
            if (data) {
                if (roomWhere) {
                    await this.modules('Building.Room').where({ company_id: id }).update({ company_id: 0 }, { transaction: t });
                    let res = await this.modules('Building.Room').where(roomWhere).update({ company_id: id }, { transaction: t });
                    if (!res) {
                        throw new Error('保存失败');
                    }
                }
                await t.commit();
                return data;
            } else {
                throw new Error('保存失败');
            }
        } catch (error) {
            await t.rollback();
            throw error;
        }

        if (data) {
            return data;
        } else {
            throw new Error('保存失败');
        }
    }

    /**
     * 删除公司
     * @return {[type]} [description]
     */
    async actionDelete() {
        let id = $_POST['id'];
        let res = await this.modules('Company').where({ id }).delete();
        if (res) {
            return true;
        } else {
            throw new Error('删除失败');
        }
    }

    /**
     * 邀请记录列表
     * @return {[type]} [description]
     */
    async actionInviteIndex() {
        let page = $_POST['page'];
        let number = page && page.number !== undefined ? page.number : 1;
        let size = page && page.size !== undefined ? page.size : 20;

        return await this.modules('Visitor.Invite').joinWith(['user']).where({ company_id: this.state.user.company_id }).page(number, size).order([
            ['id', 'DESC']
        ]).select();
    }

    /**
     * 邀请记录审核
     * @return {[type]} [description]
     */
    async actionInviteUpdate() {
        let { id, status, note } = $_POST;
        let data = {};
        if (status) {
            data['status'] = status;
        }
        if (note) {
            data['note'] = note;
        }


        return await this.modules('Visitor.Invite').where({ id, company_id: this.state.user.company_id }).update(data)
    }

}

export default AdminCompanyController;